package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yeyaomai.dksns.flowis.domain.Operator;
import com.yeyaomai.dksns.flowis.service.DownExcelService;
import com.yeyaomai.dksns.flowis.service.OperatorService;
import com.yeyaomai.dksns.flowis.service.result.DynamicXml;
import com.yeyaomai.dksns.flowis.util.Globals;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

@Controller
@RequestMapping("/operator/*")
public class OperatorController {

	@Autowired
	private OperatorService operatorService;
	
	@Autowired
	private DownExcelService downExcelService;
	
	@RequestMapping(value = "/detail")
	public ModelAndView getOperatorDetail(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String formDate = request.getParameter("formDate");
		String toDate = request.getParameter("toDate");
		String number = request.getParameter("number");
        String type = request.getParameter("type");
		String date = formDate;
		map.put("dateCount", 2);
		ModelAndView view = new ModelAndView("operator-detail");
		view.addObject("formDate", formDate);
		view.addObject("toDate", toDate);
		view.addObject("type",type);
		view.addObject("nowDate", Globals.FORMAT_TYPE_A.format(new Date()));
		view.addObject("month", VelocityToolDateUtils.getDay(Integer.valueOf("-"+Globals.FORMAT_TYPE_D.format(new Date()))+1));
		if (formDate.equals(toDate)) {
			map.put("dateCount", 1);
		}
		toDate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);

		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		Operator operator = new Operator();
		operator = operatorService.getOperatorByTime(date, toDate);
		Page<Operator> result = operatorService.getDataPage(map,
				Integer.valueOf(number));
		view.addObject("result", result);
		view.addObject("operator", operator);
		view.addObject("number", number);
		return view;
	}
	
	@RequestMapping(value = "/operatorpiexml")
	public void changePieXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("toDate") String toDate, HttpServletResponse response) throws ParseException, IOException
		{
		Map<String, Object> map = new HashMap<String, Object>();
		List<Operator> operator = new ArrayList<Operator>();
		map.put("dateCount", 2);
		String date = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", date);
		map.put("startNumber", null);
		map.put("endNumber", null);
		operator = operatorService.getOperatorByDay(map);
		String xml = DynamicXml.getOperatorPie(operator,fromDate,toDate);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	   }
	
	@RequestMapping(value = "/msLine")
	public void changeMsLineXml(HttpServletResponse response) throws ParseException, IOException
		{
		Map<String, Object> map = new HashMap<String, Object>();
		List<Operator> operator = new ArrayList<Operator>();
		map.put("dateCount",1);
		String toDate = VelocityToolDateUtils.getDay(1);
		String date = VelocityToolDateUtils.getDay(-29);
		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		map.put("startNumber", null);
		map.put("endNumber", null);
		operator = operatorService.getOperatorByDay(map);
		Map<String,Integer> operatorMap = new HashMap<String, Integer>();
		for(Operator oper:operator)
		{
			operatorMap.put(Globals.FORMAT_TYPE_A.format(oper.getReferDate())+oper.getOperatorName(), oper.getVisitCount());
		}
		String xml = DynamicXml.getOperatorMyLine(operatorMap);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	   }
	
	@RequestMapping(value = "/stackedArea")
	public void changeStackedAreaXml(HttpServletResponse response) throws ParseException, IOException
		{
		Map<String, Object> map = new HashMap<String, Object>();
		List<Operator> operator = new ArrayList<Operator>();
		map.put("dateCount",3);
		String toDate = VelocityToolDateUtils.getDay(1);
		String date = VelocityToolDateUtils.getDay(-29);
		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		map.put("startNumber", null);
		map.put("endNumber", null);
		operator = operatorService.getOperatorByDay(map);
		Map<String,Integer> operatorMap = new HashMap<String, Integer>();
		for(Operator oper:operator)
		{
			operatorMap.put(Globals.FORMAT_TYPE_A.format(oper.getReferDate()), oper.getVisitCount());
		}
		String xml = DynamicXml.getOperatorStackedArea(operatorMap);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	   }
	
	@RequestMapping(value = "/history")
	public ModelAndView getOperatorHistory(HttpServletRequest request)
			throws ParseException, UnsupportedEncodingException {
		String operator = URLDecoder.decode(request.getParameter("operatorName"),"UTF-8");
		String toDate = request.getParameter("date");
		Date date = Globals.FORMAT_TYPE_A.parse(toDate);
		Date d = null;
		String type = request.getParameter("type");
		String fromDate = "";
		if(type.equals("-1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, -30), Calendar.DATE);
			fromDate = Globals.FORMAT_TYPE_A.format(d);
		}
		else if(type.equals("1"))
		{
			d = DateUtils
					.truncate(DateUtils.addDays(date, 30), Calendar.DATE);
			String middle = toDate;
			toDate = Globals.FORMAT_TYPE_A.format(d);
			fromDate = middle;
		}
		String currentTime = Globals.FORMAT_TYPE_A.format(new Date());
		ModelAndView view = new ModelAndView("operator-history");

		if((Globals.FORMAT_TYPE_A.parse(toDate).getTime()) >= (Globals.FORMAT_TYPE_A.parse(currentTime).getTime()))
		{
			view.addObject("show", 1);
		}
		else
		{
			view.addObject("show", 0);
		}
		view.addObject("operator", URLEncoder.encode(operator,"UTF-8"));
		view.addObject("operatorName",operator);
		view.addObject("currentDate",currentTime );
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("operatorName", operator);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);
		List<Operator> operatorList = new ArrayList<Operator>();
		operatorList = operatorService.getOperatorByName(map);
		view.addObject("operatorList", operatorList);
		view.addObject("fromDate", fromDate);
		view.addObject("toDate", toDate);
		return view;
	}
	
	/**
	 * 浏览器历史柱状图展示
	 * @param fromDate 开始时间
	 * @param value 类型
	 * @param toDate 结束时间
	 * @param operaterName 接入商
	 * @param response 返回拼装数据
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/operatorhistoryxml")
	public void changeVisitAreaHistoryXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("value") String value,
			@RequestParam("toDate") String toDate, @RequestParam("operatorName") String operatorName,HttpServletResponse response) throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("operatorName", URLDecoder.decode(operatorName,"UTF-8"));
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);

		List<Operator> operatorList =operatorService.getOperatorByName(map);
		String xml = DynamicXml.getColumnByOperator(operatorList, value, fromDate,toDate);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	   // 网络接入商报表下载
		@RequestMapping(value = "down")
		public void download(HttpServletRequest request,
				HttpServletResponse response) throws ParseException,
				UnsupportedEncodingException {

			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			String todate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(endTime).getTime() + 1 * 24 * 3600 * 1000);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("fromReferDay", startTime);
			map.put("toReferDay", todate);
			map.put("startNumber", null);
			map.put("endNumber", null);
			map.put("dateCount", 1);
			List<Operator> operatorList = operatorService.getOperatorByDay(map);

			String title = "网络接入商(" + startTime + "至" + endTime + ")";
			String newTitle = URLEncoder.encode(title, "UTF-8");

			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="
					+ newTitle + ".xls");

			List<String> heads = new ArrayList<String>();
			heads.add("日期");
			heads.add("接入商名称");
			heads.add("访问次数");
			heads.add("独立访客");
			heads.add("ip");
			heads.add("新独立访客");

			List<String> pros = new ArrayList<String>();
			pros.add("referDate");
			pros.add("operatorName");
			pros.add("visitCount");
			pros.add("uniqueHost");
			pros.add("ip");
			pros.add("newUniqueHost");
			try {
				downExcelService.exportExcel(title, heads, operatorList,
						response.getOutputStream(), pros);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
}
